package shuashuami.hb.com.avtivity;

import android.app.ProgressDialog;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.wechat.friends.Wechat;
import shuashuami.hb.com.hbclient.R;
import shuashuami.hb.com.hdlibrary.util.ToastUtil;
import shuashuami.hb.com.http.HttpMethods;
import shuashuami.hb.com.http.HttpOnNextListener;
import shuashuami.hb.com.manager.HbAppManager;
import shuashuami.hb.com.manager.agent.UserManager;
import shuashuami.hb.com.share.ShareCUserInfo;
import shuashuami.hb.com.util.Consts;

/**
 * <b>类   名：</b>${TYPE_NAME} <br/>
 * <b>类描述：</b> <br/>
 * <b>创建人：</b>zhangqi<br/>
 * <b>创建时间：</b>2017/6/13<br/>
 * <b>修改人：</b>zhangqi<br/>
 * <b>修改时间：</b>2017/6/13<br/>
 * <b>修改备注：</b><br/>
 *
 * @version 1.0.0<br/>
 */
public class HbLoginAct extends AbActivity implements PlatformActionListener {

    private View selectType;   //1&#x5237;&#x624b;&#xff0c;2&#x4ee3;&#x7406;&#xff0c;3&#x5546;&#x5bb6;&#x3002;
    private Button loginBtn;
    private TextView tvRegistered;
    private LinearLayout llWeiChartLogin;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    private EditText edtPhone, edtPassword;

    private TextView tvWangjimima;

    private LinearLayout llIshow;
    private LinearLayout llaWeixin;

    private ShareCUserInfo shareCUserInfo;

    @Override
    protected void initUI() {
        setAbContentView(R.layout.act_login);
        selectType = findViewById(R.id.lin_start_type);
        loginBtn = (Button) findViewById(R.id.btn_login);
        tvRegistered = (TextView) findViewById(R.id.tv_login_to_registered);
        llWeiChartLogin = (LinearLayout) findViewById(R.id.ll_login_weichart_login);

        edtPhone = (EditText) findViewById(R.id.edt_login_phone);
        edtPassword = (EditText) findViewById(R.id.edt_login_password);
        tvWangjimima = (TextView) findViewById(R.id.tv_wangjimima);

        llIshow = (LinearLayout) findViewById(R.id.ll_login_ist_show);
        llaWeixin = (LinearLayout) findViewById(R.id.ll_toweixin);
    }

    public void onChangeLoginType(View view) {
        ((TextView) ((ViewGroup) selectType).getChildAt(0)).setTextColor(0xf0cccccc);
        ((TextView) ((ViewGroup) selectType).getChildAt(1)).setVisibility(View.INVISIBLE);
        selectType = view;
        ((TextView) ((ViewGroup) selectType).getChildAt(0)).setTextColor(Color.WHITE);
        ((TextView) ((ViewGroup) selectType).getChildAt(1)).setVisibility(View.VISIBLE);
        int tag = Integer.parseInt(selectType.getTag().toString());
        if (tag == 1) {
       //     llIshow.setVisibility(View.VISIBLE);
        } else {
       //     llIshow.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {
        HbAppManager.getInstance().SetClearableCookieJar(getApplication());
        shareCUserInfo = new ShareCUserInfo(this);
        edtPhone.setText(shareCUserInfo.getPhoneNum());
        edtPassword.setText(shareCUserInfo.getPassword());
    }

    @Override
    protected void initListener() {
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int tag = Integer.parseInt(selectType.getTag().toString());
                shareCUserInfo.setTag(tag + "");
                HbAppManager.getInstance().setLoginType(tag);
                login();
                // openActivityAndCloseThis(HbMainAct.class);
            }
        });
        tvRegistered.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int tag = Integer.parseInt(selectType.getTag().toString());
                shareCUserInfo.setTag(tag + "");
                HbAppManager.getInstance().setLoginType(tag);
                if (tag == 1) {
                    ToastUtil.showShort(HbLoginAct.this, "刷手不允许手动注册，请选择微信授权登录");
                    return;
                }
                HbAppManager.getInstance().setLoginType(tag);
                openActivity(HbRegisteredAct.class);
            }
        });
        llWeiChartLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int tag = Integer.parseInt(selectType.getTag().toString());
                shareCUserInfo.setTag(tag + "");
                HbAppManager.getInstance().setLoginType(tag);
                onWeiChartLogin();
            }
        });

        llaWeixin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//刷手
                int tag = Integer.parseInt(selectType.getTag().toString());
                shareCUserInfo.setTag(tag + "");
                HbAppManager.getInstance().setLoginType(tag);
                onWeiChartLogin();
                //   weiChartLogin("1234s56123", "");
            }
        });
        tvWangjimima.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int tag = Integer.parseInt(selectType.getTag().toString());
                shareCUserInfo.setTag(tag + "");
                HbAppManager.getInstance().setLoginType(tag);
                openActivity(WangjimimaActivity.class);
            }
        });
    }

    private void onWeiChartLogin() {
        authorize(new Wechat());
    }

    private void authorize(Wechat plat) {
        if (plat.isAuthValid()) {
            String userId = plat.getDb().getUserId();
            String icon = plat.getDb().getUserIcon();
            ShareCUserInfo shareCUserInfo = new ShareCUserInfo(this);
            shareCUserInfo.setwx_sn(userId);
            shareCUserInfo.setUserAvatar(icon);
            if (!TextUtils.isEmpty(userId)) {
                weiChartLogin(userId, icon);
                return;
            }
        }
        plat.setPlatformActionListener(this);
        plat.SSOSetting(true);
        plat.showUser(null);
    }


    private void weiChartLogin(String wxsn, String headimg) {
        progressDialog = ProgressDialog.show(this, "加载...", "请稍后...", true, false);
        HttpOnNextListener<String> listener = new HttpOnNextListener<String>() {
            @Override
            public void onNext(String s) {

                Message message = handler.obtainMessage(1);     // Message
                message.obj = s;
                handler.sendMessageDelayed(message, 0);

            }
        };

        HttpMethods.weichartLogin(listener,
                wxsn, headimg
        );
        ShareCUserInfo shareCUserInfo = new ShareCUserInfo(this);
        shareCUserInfo.setwx_sn(wxsn);
        shareCUserInfo.setUserAvatar(headimg);
    }

    final Handler handler = new Handler() {

        public void handleMessage(Message msg) {         // handle message
            switch (msg.what) {
                case 1:
                    progressDialog.dismiss();
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        if (jsonObject.getInt("status") == 200) { //成功
                            ShareCUserInfo shareCUserInfo = new ShareCUserInfo(HbLoginAct.this);
                            JSONObject temp = jsonObject.getJSONObject("content");
                            int tag = Integer.parseInt(selectType.getTag().toString());
                            if (tag == 3) {
                                shareCUserInfo.setId(temp.getString("shopId"));
                            }
                            if (tag == 1) {
                                shareCUserInfo.setId(temp.getString("brushId"));
                            }
                            if (tag == 2) {
                                shareCUserInfo.setId(temp.getString("agentId"));
                            }
                            HbAppManager.getInstance().setLoginType(tag);
                            shareCUserInfo.setTag(tag + "");
                            openActivity(HbMainAct.class);
                            finish();
                        } else if (jsonObject.getInt("status") == 400) {//初次登陆
                            openActivity(BindPhonenumActivity.class);
                        } else {
                            ToastUtil.showShort(HbLoginAct.this, jsonObject.getString("message"));
                        }
                    } catch (JSONException e) {
                        ToastUtil.showShort(HbLoginAct.this, "数据解析错误");
                    }
                    break;
                case 2:
                    progressDialog.dismiss();
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        if (jsonObject.getInt("status") == 200) { //成功
                            ShareCUserInfo shareCUserInfo = new ShareCUserInfo(HbLoginAct.this);
                            JSONObject temp = jsonObject.getJSONObject("content");
                            int tag = Integer.parseInt(selectType.getTag().toString());
                            if (tag == 3) {
                                shareCUserInfo.setId(temp.getString("shopId"));
                            }
                            if (tag == 1) {
                                shareCUserInfo.setId(temp.getString("brushId"));
                            }
                            if (tag == 2) {
                                shareCUserInfo.setId(temp.getString("agentId"));
                            }
                            shareCUserInfo.setPhoneNum(edtPhone.getText().toString());
                            shareCUserInfo.setPassword(edtPassword.getText().toString());
                            HbAppManager.getInstance().setLoginType(tag);
                            shareCUserInfo.setTag(tag + "");
                            if (HbAppManager.getInstance().getLoginType() == HbAppManager.LoginType.AGENT) {
                                String aaa = temp.getString("agentId");
                                UserManager.getInstance().getUser().setId(temp.getString("agentId"));
                            }

                            openActivity(HbMainAct.class);
                            finish();
                        } else {//初次登陆
                            ToastUtil.showShort(HbLoginAct.this, jsonObject.getString("message"));
                        }
                    } catch (JSONException e) {
                        ToastUtil.showShort(HbLoginAct.this, "数据解析错误");
                    }
                    break;
            }

            super.handleMessage(msg);
        }
    };

    private ProgressDialog progressDialog;

    private void login() {
        HttpOnNextListener<String> listener = new HttpOnNextListener<String>() {
            @Override
            public void onNext(String s) {
                //    openActivityAndCloseThis(HbRegistered2Act.class);

                Message message = handler.obtainMessage(2);     // Message
                message.obj = s;
                handler.sendMessageDelayed(message, 0);

            }
        };
        //显示ProgressDialog
        progressDialog = ProgressDialog.show(this, "加载...", "请稍后...", true, false);
        HttpMethods.login(listener,
                edtPhone.getText().toString(), edtPassword.getText().toString()
        );
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("HbLoginAct Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Consts.MSG_USERID_FOUND: {
                    Toast.makeText(HbLoginAct.this, R.string.userid_found, Toast.LENGTH_SHORT).show();
                }
                break;
                case Consts.MSG_LOGIN: {

                    String text = getString(R.string.logining, msg.obj);
                    Toast.makeText(HbLoginAct.this, text, Toast.LENGTH_SHORT).show();
                    System.out.println("---------------");

                }
                break;
                case Consts.MSG_AUTH_CANCEL: {
                    Toast.makeText(HbLoginAct.this, R.string.auth_cancel, Toast.LENGTH_SHORT).show();
                    System.out.println("-------MSG_AUTH_CANCEL--------");
                }
                break;
                case Consts.MSG_AUTH_ERROR: {
                    Toast.makeText(HbLoginAct.this, R.string.auth_error, Toast.LENGTH_SHORT).show();
                    System.out.println("-------MSG_AUTH_ERROR--------");
                }
                break;
                case Consts.MSG_AUTH_COMPLETE: {
                    //     Toast.makeText(HbLoginAct.this, R.string.auth_complete, Toast.LENGTH_SHORT).show();
                    ShareCUserInfo shareCUserInfo = new ShareCUserInfo(HbLoginAct.this);
                    weiChartLogin(shareCUserInfo.getwx_sn(), shareCUserInfo.getUserAvatar());
                    System.out.println("--------MSG_AUTH_COMPLETE-------");
                }
                break;
            }
        }
    };

    @Override
    public void onComplete(Platform platform, int action,
                           HashMap<String, Object> res) {

        Log.i("zq", "onComplete");
        if (action == Platform.ACTION_USER_INFOR) {
            ShareCUserInfo shareCUserInfo = new ShareCUserInfo(HbLoginAct.this);
            shareCUserInfo.setwx_sn(res.get("openid").toString());
            shareCUserInfo.setUserAvatar(res.get("headimgurl").toString());
            mHandler.sendEmptyMessage(Consts.MSG_AUTH_COMPLETE);
            //     login(platform.getName(), platform.getDb().getUserId(), res);
        }
        System.out.println(res);
        System.out.println("------User Name ---------" + platform.getDb().getUserName());
        System.out.println("------User ID ---------" + platform.getDb().getUserId());
    }

    public void onError(Platform platform, int action, Throwable t) {
        Log.i("zq", "onError");
        if (action == Platform.ACTION_USER_INFOR) {
            mHandler.sendEmptyMessage(Consts.MSG_AUTH_ERROR);
        }
        t.printStackTrace();
    }

    public void onCancel(Platform platform, int action) {
        Log.i("zq", "onCancel");
        if (action == Platform.ACTION_USER_INFOR) {
            mHandler.sendEmptyMessage(Consts.MSG_AUTH_CANCEL);
        }
    }
}
